/**
 * @author LKQ
 * @date 2021/12/12 20:45
 * @description 官方解法
 */
public class FormalSolution {
    public static void main(String[] args) {
        FormalSolution solution = new FormalSolution();
        solution.removeDuplicates2("abbaca");
    }

    public String removeDuplicates(String s) {
        // 官方解法，借助StringBuffer, 线程安全，但是效率低，StringBuilder线程不安全，但效率高
        StringBuffer stack = new StringBuffer();
        int top = -1;
        for (int i = 0; i < s.length(); ++i) {
            char ch = s.charAt(i);
            if (top >= 0 && stack.charAt(top) == ch) {
                stack.deleteCharAt(top);
                --top;
            } else {
                stack.append(ch);
                ++top;
            }
        }
        return stack.toString();
    }

    public String removeDuplicates2(String s) {
        // 大佬解法
        char[] chars = s.toCharArray();
        int top = -1;
        for (int i = 0; i < s.length(); i++) {
            if (top == -1 || chars[top] != chars[i]) {
                chars[++top] = chars[i];
            } else {
                top--;
            }
        }
        return String.valueOf(chars, 0, top + 1);
    }
}
